package com.example.demo.controller;

import com.example.demo.model.Klass;
import com.example.demo.service.KlassService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.UUID;

@Controller
@RequestMapping("klass")
public class KlassController {

    @Autowired
    private KlassService klassService;

    @RequestMapping("list")
    public String list(ModelMap map, Klass klass) {
        if ("".equals(klass.getName())) {
            klass.setName(null);
        }
        if ("".equalsIgnoreCase(klass.getMajor())) {
            klass.setMajor(null);
        }
        map.put("klassList", klassService.findAll(klass));
        return "klass/list";
    }

    @RequestMapping("/delete/{id}")
    public String delete(@PathVariable String id) {
        klassService.deleteById(id);
        return "redirect:/klass/list";
    }

    @RequestMapping("create")
    public String create() {
        return "klass/create";
    }

    @RequestMapping("save")
    public String save(Klass s) {
        if (s.getId() == null) {
            s.setId(UUID.randomUUID().toString());
            klassService.save(s);
        }
        else {
            klassService.update(s);
        }
        return "redirect:/klass/list";
    }

    @RequestMapping("update/{id}")
    public String update(@PathVariable String id, ModelMap map) {
        Klass s = klassService.getReferenceById(id);
        map.put("klass", s);
        return "klass/update";
    }
}
